package com.example.springboot010exceptionhandler.controller;

import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: TODO
 * @author: uu
 * @data: 2023/7/8 上午 10:31
 * @version: v1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /*@ExceptionHandler({ArithmeticException.class})
    public String HandlerArithmeticException(ArithmeticException e, Model model){
        String error = e.getMessage();
        model.addAttribute("error",error);
        return "exp";
    }*/
    @ExceptionHandler({ArithmeticException.class})
    @ResponseBody public Map<String, Object> handlerArithmeticExceptionReturnDate(ArithmeticException e){
        String error = e.getMessage();
        Map<String, Object> map = new HashMap<>();
        map.put("错误原因",e.getMessage());
        return map;
    }
    @ExceptionHandler({Exception.class})
    @ResponseBody public Map<String, Object> handleRootException(Exception e){
        String error = e.getMessage();
        Map<String, Object> map = new HashMap<>();
        map.put("错误原因",e.getMessage());
        return map;
    }

    @ExceptionHandler({BindException.class})
    public Map<String, Object> handlerJSR303Exception(BindException e){
        Map<String, Object> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()){
            List<FieldError> errors = result.getFieldErrors();
            errors.forEach(fieldError -> {
                map.put("错误[" +fieldError.getField() + "]原因", fieldError.getDefaultMessage());
            });
        }
        return map;
    }
}
